/**
 * Copyright (C) 2025 ROKAE (Beijing) Technology Co., LTD.
 * All Rights Reserved.
 *
 * Information in this file is the intellectual property of Rokae Technology Co., Ltd,
 * And may contains trade secrets that must be stored and viewed confidentially.
 *
 * @file ElectricClawWidget.cpp
 * @brief 电爪插件主界面
 */
#include "ElectricClawWidget.h"
#include "ui_ElectricClawWidget.h"

ElectricClawWidget::ElectricClawWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ElectricClawWidget)
{
    ui->setupUi(this);

    m_is_init = false;

    // 创建子线程用于轮询设备状态
    m_polling_thread = new QThread;
    m_poller = new StatusPoller(this);
    m_poller->moveToThread(m_polling_thread);

    // 轮询线程启动后执行轮询逻辑
    connect(m_polling_thread, &QThread::started, m_poller, &StatusPoller::startPolling);

    // 轮询结果信号连接到界面更新槽函数
    connect(m_poller, &StatusPoller::statusUpdated, this, [=](QJsonObject status){
        // 更新 UI
        ui->lineEdit_status->setText(QString::number(status["status"].toInt()));
        ui->lineEdit_force->setText(QString::number(static_cast<short>(status["force"].toInt())));
        ui->lineEdit_in_width->setText(QString::number(status["internal_width"].toInt()));
        ui->lineEdit_out_width->setText(QString::number(status["external_width"].toInt()));
    }, Qt::ConnectionType::QueuedConnection);

    m_polling_thread->start(); // 启动状态轮询线程

    // 设置输入框限制
    ui->lineEdit_InputToolID->setValidator(new QIntValidator(0, 255, this));
    ui->lineEdit_inputForce->setValidator(new QIntValidator(0, 140, this));
    ui->lineEdit_inputSpeed->setValidator(new QIntValidator(20, 100, this));
    ui->lineEdit_inputWidth->setValidator(new QIntValidator(160, 685, this));

    QThreadPool::globalInstance()->setMaxThreadCount(4);
}

ElectricClawWidget::~ElectricClawWidget()
{
    delete ui;
    m_polling_thread->quit();
    m_polling_thread->wait();
    delete m_polling_thread;
}

void ElectricClawWidget::sendRequest(const QJsonObject &requestJson, std::function<void (QJsonArray)> callback)
{
    auto* worker = new JsonWorker(requestJson);

    connect(worker, &JsonWorker::finished, this, [=](QJsonArray result){
        callback(result);
    }, Qt::ConnectionType::QueuedConnection);

    QThreadPool::globalInstance()->start(worker);
}

// 初始化设备，发送一次 stop 命令作为 "握手"
void ElectricClawWidget::on_pushButton_init_clicked()
{
    m_is_init = false;
    m_poller->setInit(m_is_init);

    int id = ui->lineEdit_InputToolID->text().toInt();

    QJsonObject stop_obj;
    stop_obj["slave_id"] = id;

    QJsonObject stop_root;
    stop_root["stop"] = stop_obj;

    QJsonObject root;
    root["ElectricClawPlugin"] = stop_root;

    sendRequest(root, [=](QJsonArray result){
        if (!result.isEmpty()
                && result[0].toObject()["ElectricClawPlugin"].toObject()["stop"].toObject()["return"].toBool())
        {
            m_device_id = id;
            m_is_init = true;

            m_poller->setDeviceId(m_device_id);
            m_poller->setInit(m_is_init);

            ui->lineEdit_ShowToolID->setText(QString::number(m_device_id));
            ui->lineEdit_init_status->setText(tr("Initialized"));
            ui->pushButton_run->setEnabled(true);
            ui->pushButton_stop->setEnabled(true);

            ui->lineEdit_inputForce->setEnabled(true);
            ui->lineEdit_inputSpeed->setEnabled(true);
            ui->lineEdit_inputWidth->setEnabled(true);
            ui->comboBox_mode->setEnabled(true);
        }
        else
        {
            m_is_init = false;

            m_poller->setInit(m_is_init);

            ui->lineEdit_ShowToolID->clear();
            ui->lineEdit_init_status->setText(tr("Initialization failed"));
            ui->pushButton_run->setEnabled(false);
            ui->pushButton_stop->setEnabled(false);

            ui->lineEdit_inputForce->setEnabled(false);
            ui->lineEdit_inputSpeed->setEnabled(false);
            ui->lineEdit_inputWidth->setEnabled(false);
            ui->comboBox_mode->setEnabled(false);

            ui->lineEdit_status->clear();
            ui->lineEdit_force->clear();
            ui->lineEdit_in_width->clear();
            ui->lineEdit_out_width->clear();
        }
    });
}

void ElectricClawWidget::on_pushButton_stop_clicked()
{
    if (!m_is_init)
    {
        return;
    }

    QJsonObject stop_obj;
    stop_obj["slave_id"] = m_device_id;

    QJsonObject stop_root;
    stop_root["stop"] = stop_obj;

    QJsonObject root;
    root["ElectricClawPlugin"] = stop_root;

    sendRequest(root, [=](QJsonArray){});
}

void ElectricClawWidget::on_pushButton_run_clicked()
{
    if (!m_is_init)
    {
        return;
    }

    QJsonObject start_obj;
    start_obj["slave_id"] = m_device_id;
    start_obj["mode"] = ui->comboBox_mode->currentIndex() + 1;
    start_obj["width"] = ui->lineEdit_inputWidth->text().toInt();
    start_obj["force"] = ui->lineEdit_inputForce->text().toInt();
    start_obj["speed"] = ui->lineEdit_inputSpeed->text().toInt();

    QJsonObject start_root;
    start_root["start"] = start_obj;

    QJsonObject root;
    root["ElectricClawPlugin"] = start_root;

    sendRequest(root, [=](QJsonArray){});
}

void ElectricClawWidget::showEvent(QShowEvent*)
{
    m_poller->openTimer();
}

void ElectricClawWidget::hideEvent(QHideEvent*)
{
    m_poller->closeTimer();
}
